package com.dragondig.tetris;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;

public class DataProvider extends ContentProvider {

	private static final String DATABASE_NAME = "tetris_scores";
	private static final int DATABASE_VERSION = 1;
	private static final String TABLE_NAME = "Scores";
	private DatabaseHelper mOpenHelper;
	
	
	private static class DatabaseHelper extends SQLiteOpenHelper{
		DatabaseHelper(Context context){
			super(context,DATABASE_NAME,null,DATABASE_VERSION);
		}
		@Override
		public void onCreate(SQLiteDatabase db){
			String preSQL = "CREATE TABLE" + TABLE_NAME + "("
				+ "player" + "TEXT,"
				+ "score" + "REAL,"
				+ ");";
			try{
				db.execSQL(preSQL);
			}catch(SQLException e){
				Log.e("ERROR", e.toString());
			}
		}
		@Override
		public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){}
	}
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		try{
			db.insert(TABLE_NAME, null, values);
		}catch(SQLException e){
			Log.e("ERROR", e.toString());
		}
		return uri;
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		String getAllInfoSQL = "SELECT TOP 10 player,score FROM " + TABLE_NAME
			+ " ORDER BY score DESC";
		Cursor c = db.rawQuery(getAllInfoSQL, null);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

}
